﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;
using System.Net.Sockets;
using System.Net;

namespace ECGServer
{
    class ThreadHandleData
    {
        byte[] data;
        //use when sender is client, not workstation. 
        //This is special case when client confirm UDP endpoint
        IPEndPoint clientEndPoint; 

        public ThreadHandleData(byte[] data, IPEndPoint clientEP)
        {
            this.data = data;
            this.clientEndPoint = clientEP; //this is not meaningful in case of sender is workstation
        }

        public void handleData(Object threadContext)
        {
            //Data format: [PID]|[Data] or "RequestData|[PID]|[ID]"
            //Extract patient ID information from data
            int i = 0;
            char c;
            StringBuilder sb = new StringBuilder();
            string PID;

            while (i < data.Length)
            {
                c = Convert.ToChar(data[i]);
                if (c != '|')
                {
                    sb.Append(c);
                    i++;
                }
                else
                    break;
            }
            PID = sb.ToString();

            if (PID == Constants.MSG_REQUESTDATA)
            {
                string message = System.Text.Encoding.ASCII.GetString(data);
                string[] sArr = message.Split('|');
                try
                {
                    if (ECGServer.PID_WorkStation.Contains(sArr[1]))
                    {
                        int id = Convert.ToInt32(sArr[2]);
                        //Hashtable clientHashtable = (Hashtable)ECGServer.PID_Client[sArr[1]];
                        //((Client)clientHashtable[id]).ClientUDPEndPoint = clientEndPoint;
                        Hashtable clientEndPointHT = (Hashtable)ECGServer.PID_ClientEndPoint[sArr[1]];
                        clientEndPointHT.Add(id, clientEndPoint);
                        Console.WriteLine("_______Request data message UDP from " + clientEndPoint.ToString());
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("_______Request data message UDP has wrong format");
                }
            }
            else
            {
                //Console.WriteLine("ReceiveData");
                lock (ECGServer.PID_WorkStation)
                {
                    if (ECGServer.PID_WorkStation[PID] != null)
                    {
                        ((WorkStation)ECGServer.PID_WorkStation[PID]).LastCommunicationTime = System.DateTime.Now;
                    }
                }

                //Send data to each client that registered      
                //lock (ECGServer.PID_Client)
                //{
                //    if (ECGServer.PID_Client != null && ECGServer.PID_Client.Contains(PID))
                //    {
                //        foreach (DictionaryEntry Item in (Hashtable)ECGServer.PID_Client[PID])
                //        {
                //            byte[] sendData = new byte[data.Length - (i + 1)];//pid and character '|'
                //            Buffer.BlockCopy(data, (i + 1), sendData, 0, data.Length - (i + 2));
                //            Client client = (Client)Item.Value;
                //            ECGServer.ServerUDPSocket.Send(sendData, sendData.Length, client.ClientUDPEndPoint);
                //        }
                //    }
                //}

                lock (ECGServer.PID_ClientEndPoint)
                {
                    if (ECGServer.PID_ClientEndPoint != null && ECGServer.PID_ClientEndPoint.Contains(PID))
                    {
                        foreach (DictionaryEntry Item in (Hashtable)ECGServer.PID_ClientEndPoint[PID])
                        {
                            byte[] sendData = new byte[data.Length - (i + 1)];//pid and character '|'
                            Buffer.BlockCopy(data, (i + 1), sendData, 0, data.Length - (i + 2));
                            IPEndPoint clientEndPoint = (IPEndPoint)Item.Value;
                            ECGServer.ServerUDPSocket.Send(sendData, sendData.Length, clientEndPoint);
                        }
                    }
                }
            }
        }
    }
}
